import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '@/views/home/Home'
import Login from '@/views/login/Login'
import Register from '@/views/register/Register'
import Shop from '@/views/shop/Shop'
import OrderConfirmation from '@/views/orderConfirmation/OrderConfirmation'
import Carts from '@/views/cart/Carts'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: Shop
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    beforeEnter (to, from, next) {
      if (localStorage.isLogin && to.name === 'Login') {
        next({ name: 'Home' })
        return
      }
      next()
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/carts',
    name: 'Carts',
    component: Carts
  },
  {
    path: '/orderConfirmation/:id',
    name: 'OrderConfirmation',
    component: OrderConfirmation
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (localStorage.isLogin || to.name === 'Login' || to.name === 'Register') {
    next()
    return
  }
  next({ name: 'Login' })
})

export default router
